﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ServiceEntities;
using BVCommon.Entities;
using System.Data;

// NOTE: If you change the class name "OrderService" here, you must also update the reference to "OrderService" in Web.config.
public class OrderService : IOrderService
{

    public List<Order> GetData()
    {
        List<Order> list;
        using (BtVisionEntities data = new BtVisionEntities())
        {
            list = (from p in data.Order
                    select p).ToList();
        }
        return list;
    }

    public void SaveData(IEnumerable<Order> list)
    {
        using (BtVisionEntities data = new BtVisionEntities())
        {
            IEnumerable<Order> dbList = (from p in data.Order select p).ToArray();

            //delete objects which were deleted on client
            foreach (Order item in dbList)
            {
                var identifiers = (from r in list where r.id == item.id select r);

                if (identifiers != null && identifiers.Count() == 0)
                {
                    data.DeleteObject(item);
                }
            }
            data.SaveChanges();

            try
            {
                foreach (Order item in list)
                {
                    var indentifiers = from p in dbList
                                       where p.id == item.id
                                       select p;
                    //update object
                    if (indentifiers != null && indentifiers.Count() == 1)
                    {
                        Order order = indentifiers.ElementAt(0);
                        order.order_date = item.order_date;
                        order.order_name = item.order_name;
                    }
                    //insert new object
                    else
                    {
                        data.AddToOrder(item);
                    }
                }
                data.SaveChanges();
            }
            catch (OptimisticConcurrencyException exp)
            {
                data.Refresh(System.Data.Objects.RefreshMode.ClientWins, dbList);
                data.SaveChanges();
            }

        }
    }

}
